package com.yun.many.web;

import com.baomidou.mybatisplus.annotation.IEnum;
import com.yun.many.spec.http.interceptor.RequestLoggerInterceptor;
import com.yun.many.spec.http.interceptor.TraceIdInterceptor;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.format.FormatterRegistry;
import org.springframework.util.Assert;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;
import java.util.Objects;

@Configuration
@RequiredArgsConstructor
public class WebMvcConfig implements WebMvcConfigurer {
    private final RequestLoggerInterceptor requestLoggerInterceptor;
    private final TraceIdInterceptor traceIdInterceptor;

    private static final String[] EXCLUDE_PATH = new String[]{"/health", "/ready", "/**/swagger-ui/**", "/**/swagger", "/**/api-docs/**"};

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(requestLoggerInterceptor).addPathPatterns("/**");
        registry.addInterceptor(traceIdInterceptor).addPathPatterns("/**").excludePathPatterns(EXCLUDE_PATH);
    }


    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverterFactory(new ConverterFactory<String, IEnum<?>>() {
            @Override
            public <T extends IEnum<?>> Converter<String, T> getConverter(Class<T> targetType) {
                return source -> {
                    Assert.isTrue(targetType.isEnum(), () -> "枚举类型必须实现IEnum接口");
                    return Arrays.stream(targetType.getEnumConstants())
                            .filter(t -> Objects.equals(String.valueOf(t.getValue()), source))
                            .findFirst().orElse(null);
                };
            }
        });
    }
}
